package game.socket;

import com.google.protobuf.GeneratedMessageV3;
import dou.io.ByteArrayOutput;
import dou.net.protocol.IMessageHandler;
import dou.net.socket.IClientSocket;
import dou.utils.ZLibUtil;

import java.nio.ByteBuffer;

/**
 * 消息处理抽象类
 * @author wizardc
 */
public abstract class AbstractMessageHandler implements IMessageHandler
{
    @Override
    public abstract void messageHandler(int msgID, int msgNum, GeneratedMessageV3 message, IClientSocket socket) throws Exception;

    /**
     * 编码一个消息对象为可用于发送的字节缓冲对象
     * @param msgID 消息 ID
     * @param msgNum 消息流水号
     * @param message 消息对象
     * @param compress 是否压缩
     * @throws Exception 消息处理错误时抛出该异常
     */
    protected ByteBuffer encodeMessage(int msgID, int msgNum, GeneratedMessageV3 message, boolean compress) throws Exception
    {
        byte[] contentBytes = message.toByteArray();

        ByteArrayOutput dataOutput = new ByteArrayOutput();
        dataOutput.writeUnsignedInt(9 + contentBytes.length);
        dataOutput.writeBoolean(compress);
        dataOutput.writeInt(msgID);
        dataOutput.writeInt(msgNum);
        if (compress)
        {
            contentBytes = ZLibUtil.compress(contentBytes);
        }
        dataOutput.writeBytes(contentBytes);

        return ByteBuffer.wrap(dataOutput.bytes());
    }
}
